package com.jc.nio.handlers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.ByteChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.jc.nio.process.HttpOperation;
import com.jc.nio.process.Processor;

/**
 * 这个handler的主要工作是负责对通道进行处理，它将接收到的信息交由Processor处理,Processor才是进行处理的核心类，
 * 而这个类只是进行读取上的操作
 * 
 * @author Joeson
 * @since 2014/05
 * @version 01
 */
public class NioReadHandler implements NioHandler
{

	private HttpOperation operation = null;
	private ByteBuffer receive = null;

	public NioReadHandler(HttpOperation operation, ByteBuffer receive)
	{
		this.operation = operation;
		this.receive = receive;
	}

	@Override
	public void handdler(SocketChannel channel)
	{
		receive.clear();

		try
		{
			channel.read(receive);
			// 进行解码的过程
			Charset charset = Charset.forName("UTF-8");
			CharsetDecoder decoder = charset.newDecoder();

			receive.flip();
			String msg = decoder.decode(receive).toString();

			// 由HttpOperation进行业务处理
			operation.process(msg);

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}